package com.smarth.zhizulian.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.gyf.barlibrary.ImmersionBar;
import com.smarth.zhizulian.R;
import com.smarth.zhizulian.adapter.BottomPagerAdapter;
import com.smarth.zhizulian.adapter.BottomTabProvider;
import com.smarth.zhizulian.app.BaseConfig;
import com.smarth.zhizulian.app.EventActivity;
import com.smarth.zhizulian.bean.message.MessageUserMessage;
import com.smarth.zhizulian.bean.message.MsgActivity;
import com.smarth.zhizulian.bean.user.MineIndex;
import com.smarth.zhizulian.entity.EventBean;
import com.smarth.zhizulian.fragment.HongBaoFragment;
import com.smarth.zhizulian.fragment.IndexFragment;
import com.smarth.zhizulian.fragment.InviteFragment;
import com.smarth.zhizulian.fragment.MineFragment;
import com.smarth.zhizulian.fragment.VideoIndexFragment;
import com.smarth.zhizulian.http.KumaHttp;
import com.smarth.zhizulian.http.observer.ProgressObserver;
import com.smarth.zhizulian.http.utils.RxCompos;
import com.smarth.zhizulian.popupwindow.CoinDialog;
import com.smarth.zhizulian.popupwindow.FriendHongBaoDialog;
import com.smarth.zhizulian.popupwindow.GetOneDialog;
import com.smarth.zhizulian.popupwindow.MissionHongBaoDialog;
import com.smarth.zhizulian.popupwindow.UnLoginHongBaoDialog;
import com.smarth.zhizulian.popupwindow.WarningDialog;
import com.smarth.zhizulian.utils.AutoUtils;
import com.smarth.zhizulian.utils.GsonUtils;
import com.smarth.zhizulian.utils.KumaDialogFactory;
import com.smarth.zhizulian.utils.KumaLog;
import com.smarth.zhizulian.utils.SPUtils;
import com.smarth.zhizulian.utils.UserUtils;
import com.smarth.zhizulian.view.UnScrollViewPager;
import com.ogaclejapan.smarttablayout.SmartTabLayout;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.umeng.analytics.MobclickAgent;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.functions.Consumer;

/**
 * Created by 18865 on 2017/12/23.
 */

public class MainActivity extends EventActivity {
    @BindView(R.id.vpMain)
    UnScrollViewPager vpMain;
    //    @BindView(R.id.pn_pagenavigation)
//    PageNavigationView pnPagenavigation;
    @BindView(R.id.ll_all)
    LinearLayout ll_all;
    @BindView(R.id.tl_bottom)
    SmartTabLayout tlBottom;
    public static final String INTENT_MODE = "INTENT_MODE";
    public static final String INTENT_ISSHOWDIALOG = "INTENT_ISSHOWDIALOG";
    public static final int MODE_NORMAL = 0;
    public static final int MODE_DISCIPLE = 1;
    public static final int MODE_HIGH = 2;  //分享高价文章
    private int mMode;
    private boolean mIsFirstOnWindowFocusChanged = true;
    private boolean isShowDialog = true;

    private RelativeLayout index_ll_main;
    private LinearLayout index_ll_refresh;
    private RelativeLayout video_ll_main;
    private LinearLayout video_ll_refresh;
    private ImageView iv_message;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        AutoUtils.setSize(this, Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT, 750, 1334);
        mMode = getIntent().getIntExtra(INTENT_MODE, 0);
        isShowDialog = getIntent().getBooleanExtra(INTENT_ISSHOWDIALOG, true);
        ButterKnife.bind(this);
        initTabs();
        fetchMessage();
        initPermission();
//        new GetOneDialog(mContext).show();
        MobclickAgent.openActivityDurationTrack(false);
    }

    private void initPermission() {
        new RxPermissions(mContext)
                .request(Manifest.permission.READ_EXTERNAL_STORAGE
                        , Manifest.permission.WRITE_EXTERNAL_STORAGE

                )
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                    }
                });
    }

    private void showMission() {
        try {
            KumaLog.kuma("showMission");
            if (UserUtils.isLogin() && isShowDialog) {
                Date date = new Date();
                String dateJson = SPUtils.getString(BaseConfig.SP.TODAY_DATE, "");
                if (!TextUtils.isEmpty(dateJson)) {
                    Date oldDate = GsonUtils.fromJson(dateJson, Date.class);
                    if (date.after(oldDate) && date.getDay() > oldDate.getDay()) {
                        new MissionHongBaoDialog(mContext).show();
                    }
                } else {
                    new MissionHongBaoDialog(mContext).show();
                }
                SPUtils.saveString(BaseConfig.SP.TODAY_DATE, GsonUtils.toJson(new Date()));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void showHongBao() {
        try {
            KumaLog.kuma("showHongBao");
            if (!UserUtils.isLogin() && !SPUtils.getBoolean(BaseConfig.SP.ONCE_LOGIN, false)) {
                new UnLoginHongBaoDialog(mContext).show();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void fetchMessage() {
        if (UserUtils.isLogin() && isShowDialog) {
            KumaHttp.getService().messageUserMessage()
                    .compose(RxCompos.<MessageUserMessage>getBELoginCompos())
                    .subscribe(new ProgressObserver<MessageUserMessage>(mContext, false) {
                        @Override
                        public void onNext(MessageUserMessage messageUserMessage) {
                            if (messageUserMessage.getStatus() == 1) {
                                switch (messageUserMessage.getType()) {
                                    case 101001:
                                        //清零
                                        new WarningDialog(mContext).show();
                                        break;
                                    case 102001:
                                        //活动结束
                                        MsgActivity msgActivity = GsonUtils.fromJson(messageUserMessage.getMessage(), MsgActivity.class);
                                        KumaDialogFactory.buildActivityResultDialog(mContext, msgActivity.getRank(), msgActivity.getMoney()).show();
                                        break;
                                }
                            } else {
                                showMission();
                            }
                        }

                    });
        }
    }

    private void initTabs() {
        List<Fragment> fragmentList = new ArrayList<>();
        IndexFragment indexFragment = new IndexFragment();
        fragmentList.add(indexFragment);
        fragmentList.add(new VideoIndexFragment());
        fragmentList.add(new HongBaoFragment());
        fragmentList.add(new InviteFragment());
        fragmentList.add(new MineFragment());

        List<String> titleList = new ArrayList<>();
        titleList.add("首页");
        titleList.add("视频");
        titleList.add("红包");
        titleList.add("收徒");
        titleList.add("我的");

        List<Integer> iconList = new ArrayList<>();
        iconList.add(R.drawable.bottom_index_selector);
        iconList.add(R.drawable.bottom_video_selector);
        iconList.add(R.drawable.bottom_hongbao_selector);
        iconList.add(R.drawable.bottom_disciple_selector);
        iconList.add(R.drawable.bottom_mine_selector);

        BottomPagerAdapter pagerAdapter = new BottomPagerAdapter(mContext, getSupportFragmentManager(), fragmentList, titleList, iconList);
        vpMain.setAdapter(pagerAdapter);
        vpMain.setOffscreenPageLimit(5);
        vpMain.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                switch (position) {
                    case 0:
                        index_ll_main.setVisibility(View.GONE);
                        index_ll_refresh.setVisibility(View.VISIBLE);
                        video_ll_main.setVisibility(View.VISIBLE);
                        video_ll_refresh.setVisibility(View.GONE);
                        initDarkStatusBar();
                        break;
                    case 1:
                        index_ll_main.setVisibility(View.VISIBLE);
                        index_ll_refresh.setVisibility(View.GONE);
                        video_ll_main.setVisibility(View.GONE);
                        video_ll_refresh.setVisibility(View.VISIBLE);
                        initDarkStatusBar();
                        break;
                    case 2:
                        index_ll_main.setVisibility(View.VISIBLE);
                        index_ll_refresh.setVisibility(View.GONE);
                        video_ll_main.setVisibility(View.VISIBLE);
                        video_ll_refresh.setVisibility(View.GONE);
                        initDarkStatusBar();
                        break;
                    case 3:
                        index_ll_main.setVisibility(View.VISIBLE);
                        index_ll_refresh.setVisibility(View.GONE);
                        video_ll_main.setVisibility(View.VISIBLE);
                        video_ll_refresh.setVisibility(View.GONE);
                        initDarkStatusBar();
                        break;
                    case 4:
                        index_ll_main.setVisibility(View.VISIBLE);
                        index_ll_refresh.setVisibility(View.GONE);
                        video_ll_main.setVisibility(View.VISIBLE);
                        video_ll_refresh.setVisibility(View.GONE);
                        initHoloStatusBar();
                        break;
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        tlBottom.setCustomTabView(new BottomTabProvider(mContext));
        tlBottom.setViewPager(vpMain);
        View indexTab = tlBottom.getTabAt(0);
        View videoTab = tlBottom.getTabAt(1);
        View mineTab = tlBottom.getTabAt(4);
        index_ll_main = indexTab.findViewById(R.id.ll_main);
        index_ll_refresh = indexTab.findViewById(R.id.ll_refresh);
        video_ll_main = videoTab.findViewById(R.id.ll_main);
        video_ll_refresh = videoTab.findViewById(R.id.ll_refresh);
        index_ll_main.setVisibility(View.GONE);
        index_ll_refresh.setVisibility(View.VISIBLE);
        iv_message = mineTab.findViewById(R.id.iv_message);
    }

    public static void openClearTask(Context context, int mode) {
        Intent i = new Intent(context, MainActivity.class);
        i.putExtra(INTENT_MODE, mode);
        i.putExtra(INTENT_ISSHOWDIALOG, false);
        context.startActivity(i);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        KumaLog.kuma("onNewIntent");
        mMode = intent.getIntExtra(INTENT_MODE, 0);
        switch (mMode) {
            case MODE_NORMAL:
                vpMain.setCurrentItem(0);
                EventBus.getDefault().post(new EventBean(BaseConfig.EventCode.SHOW_FIRST, "MainActivity"), "IndexFragment");
                break;
            case MODE_DISCIPLE:
                vpMain.setCurrentItem(3);
                EventBus.getDefault().post(new EventBean(BaseConfig.EventCode.SHOW_INVITEDICIPLE, "MainActivity"), "InviteFragment");
                break;
            case MODE_HIGH:
                vpMain.setCurrentItem(0);
                EventBus.getDefault().post(new EventBean(BaseConfig.EventCode.SHOW_HIGH, "MainActivity"), "IndexFragment");
                break;
        }
    }

    public static void openRestart(Context context) {
        Intent i = new Intent(context, MainActivity.class);
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
                Intent.FLAG_ACTIVITY_CLEAR_TASK);
        i.putExtra(INTENT_ISSHOWDIALOG, false);
        context.startActivity(i);
    }

    public static void openClearTaskShowMission(Context context, int mode) {
        Intent i = new Intent(context, MainActivity.class);
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
                Intent.FLAG_ACTIVITY_CLEAR_TASK);
        i.putExtra(INTENT_MODE, mode);
        i.putExtra(INTENT_ISSHOWDIALOG, true);
        context.startActivity(i);
    }

    private long firstTime;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            long secondTime = System.currentTimeMillis();
            if (secondTime - firstTime > 2000) {
                Toast.makeText(MainActivity.this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                firstTime = secondTime;
                return true;
            } else {
                System.exit(0);
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        if (mIsFirstOnWindowFocusChanged && hasFocus) {
//            showLockScreenPopUpWindow();
            mIsFirstOnWindowFocusChanged = false;
            showHongBao();
        }
    }

    @Override
    protected void initStatusBar() {
        ImmersionBar.with(this)
                .transparentStatusBar()
                .statusBarDarkFont(true)
                .fitsSystemWindows(false)
                .init();
    }

    @Subscriber(tag = "MainActivity")
    private void onEvent(EventBean eb) {
        switch (eb.getCode()) {
            case BaseConfig.EventCode.SHOW_INVITEDICIPLE:
                vpMain.setCurrentItem(3);
                break;
            case BaseConfig.EventCode.SHOW_ARTICLE:
                vpMain.setCurrentItem(0);
                break;
            case BaseConfig.EventCode.ON_GET_MINE:
                MineIndex mi = (MineIndex) eb.getBody();
                if (mi.getIsMessageApp() == 1 || mi.getIsMessageNotice() == 1) {
                    iv_message.setVisibility(View.VISIBLE);
                } else {
                    iv_message.setVisibility(View.GONE);
                }
                break;
        }
    }

    private void initDarkStatusBar() {
        ImmersionBar.with(this)
                .transparentStatusBar()
                .statusBarDarkFont(true)
                .fitsSystemWindows(false)
                .init();
    }

    private void initHoloStatusBar() {
        ImmersionBar.with(this)
                .transparentStatusBar()
                .statusBarDarkFont(false)
                .fitsSystemWindows(false)
                .init();
    }

}
